package jrain.fw.core.http;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import jrain.utils.consts.BaseConst;
import jrain.utils.lang.StringUtils;

public class HttpResponse {

	public static final String CONTENT_TYPE = "Content-Type";

	private String url;

	private int status = 200;

	private String encoding = BaseConst.UTF8.name();

	private HttpContentFormatType httpContentType = null;

	private Map<String, String> header = new HashMap<String, String>();

	private byte[] contents;

	private String data;

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getEncoding() {
		return encoding;
	}

	public void setEncoding(String encoding) {
		this.encoding = encoding;
	}

	public int getStatus() {
		return status;
	}

	public void setStatus(int status) {
		this.status = status;
	}

	public Map<String, String> getHeader() {
		return header;
	}

	public void setHeader(Map<String, String> header) {
		this.header = header;
	}

	public String getHeader(String key) {
		return this.header.get(key);
	}

	public void putHeader(String key, String value) {
		this.header.put(key, value);
	}

	public void removeHeader(String key) {
		this.header.remove(key);
	}

	public void clearHeader(String key) {
		this.header.clear();
	}

	public HttpContentFormatType getHttpContentType() {
		return httpContentType;
	}

	public void setHttpContentType(HttpContentFormatType httpContentType) {
		this.httpContentType = httpContentType;
		if (this.httpContentType != null) {
			putHeader(CONTENT_TYPE, getContentTypeValue(this.httpContentType, this.encoding));
		}
	}

	private String getContentTypeValue(HttpContentFormatType contentType, String encoding) {
		if (null != contentType && null != encoding) {
			return HttpContentFormatType.mapFormatToAccept(contentType) + ";charset=" + encoding.toLowerCase();
		} else if (null != contentType) {
			return HttpContentFormatType.mapFormatToAccept(contentType);
		}
		return null;
	}

	public void setData(String data) {
		this.data = data;
	}

	public String getData() {
		if (data != null && data.length() > 0) {
			return data;
		}
		String encoding = StringUtils.trimNull(this.encoding, BaseConst.UTF8.name());
		try {
			return new String(getContents(), encoding);
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}

	public byte[] getContents() {
		return contents;
	}

	public void setContents(byte[] contents) {
		this.contents = contents;
	}

}
